package com.cyc.quick.token;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.cyc.quick.constants.Constant;
import com.cyc.quick.exception.ProjectException;
import com.cyc.quick.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fei
 */
@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 创建token
     *
     * @return token
     */
    @Override
    public String createToken() {
        String token = RandomUtil.randomString(20);
        StrBuilder redisToken = new StrBuilder();
        try {
            redisToken.append(Constant.Redis.TOKEN_PREFIX).append(token);
            redisUtil.setEx(redisToken.toString(), token, 10000L);
            boolean notEmpty = StrUtil.isNotEmpty(token);
            if (notEmpty) {
                return token;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 检验token
     *
     * @param request 请求request
     */
    @Override
    public boolean checkToken(HttpServletRequest request) {

        String token = request.getHeader(Constant.TOKEN_NAME);
        if (StrUtil.isBlank(token)) {
            // header中不存在token
            token = request.getParameter(Constant.TOKEN_NAME);
            if (StrUtil.isBlank(token)) {
                // parameter中也不存在token
                throw new ProjectException("100", "非法访问,缺少token");
            }
        }

        if (!redisUtil.exists(Constant.Redis.TOKEN_PREFIX + token)) {
            log.info("重复访问或token错误");
            throw new ProjectException("200", "请勿重复点击");
        }
        //访问成功后, 删除redis中该token ,
        boolean remove = redisUtil.remove(Constant.Redis.TOKEN_PREFIX + token);
        if (!remove) {
            throw new ProjectException("200", "移除token失败");
        }
        return true;
    }
}
